﻿
Imports osi.root.formation
Imports osi.root.connector
Imports osi.root.utils
Imports osi.root.delegates
Imports osi.root.threadpool
Imports System.Threading

Friend Class threadpool_case
    Private ReadOnly size As Int64
    Private ReadOnly w As void
    Private ReadOnly before As void
    Private ReadOnly after As void

    Public Sub New(ByVal size As Int64,
                   ByVal w As void,
                   Optional ByVal before As void = Nothing,
                   Optional ByVal after As void = Nothing)
        assert(size > 0)
        assert(Not w Is Nothing)
        Me.size = size
        Me.w = w
        Me.before = before
        Me.after = after
    End Sub

    Private Shared Sub queue_job(ByVal tp As ithreadpool, ByRef size As Int64, ByVal w As void)
        assert(Not tp Is Nothing)
        assert(Not w Is Nothing)
        While Interlocked.Decrement(size) >= 0
            tp.queue_job(w)
        End While
    End Sub

    Private Sub queue_job(ByVal tp As ithreadpool)
        Dim size As Int64 = 0
        size = Me.size
        For i As Int32 = 0 To (Environment.ProcessorCount() >> 1) - 1
            Dim t As Thread = Nothing
            t = New Thread(Sub()
                               queue_job(tp, size, w)
                           End Sub)
            t.Start()
        Next
        timeslice_sleep_wait_until(Function() size <= 0)
    End Sub

    Private Function run_case() As Boolean
        Dim p As pointer(Of Int64) = Nothing
        p = New pointer(Of Int64)()
        Dim tp As ithreadpool = Nothing
        Using c = New ms_timing_counter(p)
            tp = resolver.resolve(Of ithreadpool)()
            If assert(Not tp Is Nothing) Then
                void_(before)
                queue_job(tp)
            End If
            Using New thread_lazy()
                timeslice_sleep_wait_until(Function() tp.idle())
            End Using
            void_(after)
        End Using
        If Not tp Is Nothing Then
            raise_error("finished threadpool ", tp.GetType().FullName(), " test, used time in milliseconds ", +p)
        End If
        Return True
    End Function

    Public Function run() As Boolean
        register_managed_threadpool()
        run_case()
        register_slimqless2_threadpool()
        run_case()
        register_qless_threadpool()
        run_case()
        Return True
    End Function
End Class
